<?php
/**
 * Created by PhpStorm.
 * User: Sunqj
 * Date: 2017/1/17
 * Time: 下午11:48
 */

use think\Cache;

/**
 * 生成管理员权限
 *
 * @param $role
 */
function generate_admin_authority($role)
{
    //权限列表
    $authorityList = get_all_authorities();

    //html 内容
    $html = "";

    foreach ($authorityList as $authority)
    {
        $html .= generate_role_authority($role, $authority);
    }

    echo $html;
}

/**
 * 根据角色生成权限
 *
 * @param array $role 角色数据
 * @param array $authority 权限
 * @return string
 */
function generate_role_authority($role, $authority)
{
    //HTML 内容
    $html = "";

    //行首
    $html .= "<div class='row'><div class='col-xs-12'>";

    //判断是否拥有权限
    $hasAuthority = has_authority($authority["authority"], $role["authority"]) ? "checked" : "";

    //输入权限
    $html .= "<label class='checkbox-inline dakq-role-title'>";
    $html .= "<input data-type='role-" . $authority["name"]
        . "' data-toggle='role-title' type='checkbox' name='authority[]' value='"
        . $authority["authority"] . "' " . $hasAuthority . ">" . $authority["title"] . "</label>";

    //获取子级权限
    $children = $authority["children"];
    foreach ($children as $child)
    {
        //判断是否拥有权限
        $hasAuthority = has_authority($child["authority"], $role["authority"]) ? "checked" : "";

        $html .= "<label class='checkbox-inline'>";
        $html .= "<input data-type='role-" . $authority["name"]
            . "' data-toggle='role-item' type='checkbox' name='authority[]' value='"
            . $child["authority"] . "' " . $hasAuthority . ">" . $child["title"] . "</label>";
    }

    //行尾
    $html .= "</div></div>";

    return $html;
}

/**
 * 获取所有的权限信息
 *
 * @return mixed
 */
function get_all_authorities()
{
    if (Cache::has("admin_authority"))
    {
        return Cache::get("admin_authority");
    }
    else
    {
        //读取菜单配置
        $config = file_get_contents(__DIR__ . '/' . "authority.json");

        //权限列表
        $authorityList = json_decode($config, true);

        Cache::set("admin_authority", $authorityList);

        return $authorityList;
    }
}

/**
 * 解析权限
 *
 * @param $authority
 * @return string
 */
function parse_authority($authority)
{
    //获取所有权限
    $authorityList = get_all_authorities();
    foreach ($authorityList as $item)
    {   if ($item["authority"] == $authority)
        {
            return $item["title"];
        }
        $children = $item["children"];

        foreach ($children as $child)
        {
            if ($child["authority"] == $authority)
            {
                return $child["title"];
            }
        }
    }

    return "未知权限";
}

/**
 * 判断权限是否存在
 *
 * @param $name
 * @param $list
 * @return bool
 */
function has_authority($name, $list)
{
    return in_array($name, $list);
}